package com.flowable.controller;

import com.flowable.entity.ProcessInstanceVO;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.HistoryService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/processes") // 接口统一前缀
public class ProcessInstanceController {

    @Autowired
    private RuntimeService runtimeService; // 运行中的流程实例

    @Autowired
    private HistoryService historyService; // 历史流程实例（已结束）

    // 格式化时间的工具
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取所有流程实例（包括运行中+已结束）
     */
    @GetMapping
    public List<ProcessInstanceVO> getAllProcesses() {
        List<ProcessInstanceVO> result = new ArrayList<>();

        // 1. 查询运行中的流程实例
        List<ProcessInstance> runningInstances = runtimeService.createProcessInstanceQuery().list();
        for (ProcessInstance instance : runningInstances) {
            ProcessInstanceVO vo = new ProcessInstanceVO();
            vo.setId(instance.getId());
            vo.setProcessDefinitionKey(instance.getProcessDefinitionKey());
            vo.setProcessDefinitionName(instance.getProcessDefinitionName());
            vo.setStartTime(sdf.format(instance.getStartTime()));
            vo.setStatus("申请中");
            vo.setStartedBy(instance.getStartUserId()); // 需流程启动时设置了发起人
            // 关键：通过流程实例ID获取"days"变量（请假天数）

            Object daysObj = runtimeService.getVariable(instance.getId(), "days");
            if (daysObj != null) {
                // 根据实际存储类型转换（通常是Integer或String）
                vo.setDuration(daysObj.toString()); // 如"3天"
                // 若存储的是数字，也可直接强转：(Integer) daysObj
            } else {
                vo.setDuration("未知"); // 变量不存在时的默认值
            }

            // 2. 获取并设置申请人（关键代码）
            Object applicantObj = runtimeService.getVariable(instance.getId(), "applicant");
            if (applicantObj != null) {
                // 申请人可能是姓名（如"张三"）或用户ID，根据实际存储类型处理
                vo.setApplicant(applicantObj.toString());
            } else {
                vo.setApplicant("未知申请人");
            }

            System.err.println(vo);
            result.add(vo);
        }

        // 2. 查询已结束的流程实例（从历史记录中）
        List<HistoricProcessInstance> endedInstances = historyService.createHistoricProcessInstanceQuery()
                .finished() // 低版本中表示“已结束”
                .list();
        for (HistoricProcessInstance instance : endedInstances) {
            ProcessInstanceVO vo = new ProcessInstanceVO();
            vo.setId(instance.getId());
            vo.setProcessDefinitionKey(instance.getProcessDefinitionKey());
            vo.setProcessDefinitionName(instance.getProcessDefinitionName());
            vo.setStartTime(sdf.format(instance.getStartTime()));
            vo.setStatus("已完成");
            vo.setStartedBy(instance.getStartUserId());
            // 1. 获取请假天数
            HistoricVariableInstance daysVar = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(instance.getId())
                    .variableName("days")
                    .singleResult();
            if (daysVar != null) {
                vo.setDuration(daysVar.getValue().toString());
            } else {
                vo.setDuration("未知");
            }

            // 2. 获取申请人
            HistoricVariableInstance applicantVar = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(instance.getId())
                    .variableName("applicant")
                    .singleResult();
            if (applicantVar != null) {
                vo.setApplicant(applicantVar.getValue().toString());
            } else {
                vo.setApplicant("未知申请人");
            }

            result.add(vo);
        }

        System.err.println(result);

        return result;
    }
}